import { createRouter, createWebHistory } from "vue-router";

import localCache from "../utils/cache";

import { firstMenu, menuToRouter } from "../utils/map-menu";

const routes = [
  {
    path: "/",
    redirect: "/main",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),
  },
  {
    path: "/main",
    name: "main",
    component: () => import("../views/layout.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("../views/not-found/not-found.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export function addRoutesWithMenu(menus) {
  // 1.获取匹配到的所有的路由
  const routes = menuToRouter(menus);
  for (const route of routes) {
    router.addRoute("main", route);
  }
}

router.beforeEach((to) => {
  const token = localCache.getItem("token");
  if (to.path !== "/login") {
    if (!token) {
      return "/login";
    }
  }

  if (to.path === "/main") {
    return firstMenu.url;
  }

  if (to.meta && to.meta.title) {
    document.title = "cms" + " - " + to.meta.title;
  }
});

export default router;
